package com.lmq.singleton;


import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class LazyMan {
    private static boolean lmqiao=false;

    private LazyMan(){
        synchronized (LazyMan.class){
            if (lmqiao==false){
                lmqiao=true;
            } else {
                throw new RuntimeException("不要试图使用反射破坏异常");
            }
//            if (lazyMan!=null){
//                throw new RuntimeException("不要试图使用反射破坏异常");
//            }
        }

//        System.out.println(Thread.currentThread().getName()+"ok");
    }

    private volatile static LazyMan lazyMan;


    public static LazyMan getInstance(){
        //加lock,双重检测锁，DCL
        if (lazyMan==null){
            synchronized (LazyMan.class){
                if (lazyMan==null){
                    lazyMan=new LazyMan();
                }

            }
        }

        return lazyMan;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                System.out.println(LazyMan.getInstance());

            }).start();

        }
    }
//反射
//    public static void main(String[] args) throws Exception {
////        LazyMan instance = LazyMan.getInstance();
//
//
//        Field lmqiao = LazyMan.class.getDeclaredField("lmqiao");
//        lmqiao.setAccessible(true);
//
//        Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
//        declaredConstructor.setAccessible(true);
//        LazyMan instance = declaredConstructor.newInstance();
//
//        lmqiao.set(instance,false);
//
//        LazyMan instance2 = declaredConstructor.newInstance();
//
//        System.out.println(instance2);
//        System.out.println(instance);
//
//
//    }
}

